package inits

import (
	"app-webapi/comm/g"
	"errors"
	"fmt"
	influxdb "github.com/influxdata/influxdb1-client/v2"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func Db() {
	persistPath, err := g.AppService.GetAppSetting("PersistPath")
	if err != nil {
		panic(err)
	}
	g.PersistPath = persistPath
	db, err := gorm.Open(sqlite.Open(persistPath+g.ServiceKey+".db"), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Warn),
	},
	)

	if err != nil {
		panic(err)
	}
	// 启用 WAL 模式
	_ = db.Exec("PRAGMA journal_mode=WAL;")
	sqlDB, dbError := db.DB()
	if dbError != nil {
		panic(dbError)
	}
	sqlDB.SetMaxIdleConns(100)
	sqlDB.SetMaxOpenConns(10)
	debug, err := g.AppService.GetAppSetting("GormDebug")
	if debug == "true" {
		db = db.Debug()
	}

	g.Db = db
}

func RecordNotFound(e error) bool {
	return errors.Is(e, gorm.ErrRecordNotFound)
}

func InfluxDB() {
	influxdbAddr, _ := g.AppService.GetAppSetting("InfluxdbAddr")
	influxdbUser, _ := g.AppService.GetAppSetting("InfluxdbUser")
	influxdbPassword, _ := g.AppService.GetAppSetting("InfluxdbPassword")
	cli, err := influxdb.NewHTTPClient(influxdb.HTTPConfig{
		Addr:     influxdbAddr,
		Username: influxdbUser,
		Password: influxdbPassword,
	})
	if err != nil {
		fmt.Println("Error creating InfluxDB Client: ", err.Error())
	} else {
		g.InfluxDbClient = cli
		fmt.Println("creating InfluxDB Client Success ")
	}
}
